<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon class="relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div class="absolute top-4px right-10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #tableTitle>
        <div class="ml-2">
          <span>报警列表</span>
        </div>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: ICON.EXPORT,
                tooltip: {
                  title: '导出CSV',
                  placement: 'top',
                },
                onClick: handleDownload.bind(null, { alarmId: record.id }),
              },
              {
                icon: ICON.COMMENT,
                tooltip: {
                  title: '评论',
                  placement: 'top',
                },
                onClick: openModal.bind(null, true, {
                  alarmId: record.id,
                  acknowledged: record.acknowledged,
                  cleared: record.cleared,
                }),
              },
              {
                icon: ICON.CHECK,
                tooltip: {
                  title: '详情',
                  placement: 'top',
                },
                onClick: openDrawer.bind(null, true, {
                  entityType: ENTITY_TYPE.ALARM,
                  entityId: record.id,
                  title: '告警详细信息',
                  detailSchema: detailSchema,
                  record: record,
                }),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <CommentModal @register="registerModal" />
    <PublicDrawer @register="registerDrawer" :showTabs="['detail']" />
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import CommentModal from './components/CommentModal.vue';
  import { columns, searchFormSchema } from './alarm.data';
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import { detailSchema } from './components/AlarmDrawer.data';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';
  import Icon from '/@/components/Icon';
  import { Alert, Tooltip } from 'ant-design-vue';
  import { ICON } from '/@/enums/iconEnum';
  import {
    alarmsPage,
    assignUsers,
    unassignedUsers,
    entityAlarmsPage,
    deleteAlarm,
  } from '/@/api/thingsborad/alarm';
  import { useDrawer } from '/@/components/Drawer';
  import { getAlarmComment } from '/@/api/thingsborad/alarm';
  import { aoaToSheetXlsx } from '/@/components/Excel';
  import { useMessage } from '/@/hooks/web/useMessage';
  import dayjs from 'dayjs';
  import { onMounted, ref } from 'vue';
  import {
    tableFormStyleSetting,
    publicDrawerTableFormStyleSetting,
    tableStyleSetting,
  } from '/@/settings/thingsBoardDesign';

  const props = defineProps({
    isComponent: {
      type: Boolean,
      default: true,
    },
    entityType: {
      type: String,
    },
    entityId: {
      type: String,
    },
  });
  const checkedKeys = ref<any>([]);
  const [registerTable, { reload, getDataSource, setProps }] = useTable({
    columns: columns,
    ...tableStyleSetting,
    beforeFetch: (data) => {
      let temp: any = {
        pagination: {
          pageSize: data.pageSize,
          page: data.page - 1,
        },
      };
      if (props.isComponent) {
        temp.entityType = props.entityType;
        temp.entityId = props.entityId;
      }
      data.textSearch ? (temp.pagination.textSearch = data.textSearch) : null;
      data.status ? (temp.pagination.statusList = data.status.join(',')) : null;
      data.severity ? (temp.pagination.severityList = data.severity.join(',')) : null;
      data.type ? (temp.pagination.typeList = data.type.join(',')) : null;
      data.assigneeId ? (temp.pagination.assigneeId = data.assigneeId) : null;
      if (data.field && data.order) {
        temp.pagination.sortProperty = data.field;
        if (data.order == 'ascend') {
          temp.pagination.sortOrder = 'ASC';
          return temp;
        } else {
          temp.pagination.sortOrder = 'DESC';
          return temp;
        }
      } else {
        return temp;
      }
    },
    afterFetch: (data) => {
      data.forEach((item) => {
        item.id = item.id.id;
        if (item.assignee) {
          item.assignOptionsValue =
            item.assignee.firstName && item.assignee.lastName
              ? item.assignee.firstName + '  ' + item.assignee.lastName
              : item.assignee.email;
        } else {
          item.assignOptionsValue = '未分配';
        }
      });
      return data;
    },
    formConfig: {
      showAdvancedButton: false,
      schemas: searchFormSchema,
      ...tableFormStyleSetting,
      labelCol: {
        style: {
          marginBottom: '24px',
        },
      },
      actionColOptions: {
        md: { span: 8, offset: 0 },
        lg: { span: 6, offset: 12 },
        xl: { span: 4, offset: 0 },
        xxl: { span: 4, offset: 0 },
      },
    },
    beforeEditSubmit: async ({ value, index }) => {
      const tableData = getDataSource();
      if (value == 'unassigned') {
        let params = {
          alarmId: tableData[index].id.id,
        };
        await unassignedUsers(params);
      } else {
        let params = {
          alarmId: tableData[index].id,
          assigneeId: value,
        };
        await assignUsers(params);
        reload();
      }
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerModal, { openModal }] = useModal();
  const { createConfirm } = useMessage();
  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected, _selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  // 多选删除
  function handleSelectedDelete() {
    createConfirm({
      iconType: 'info',
      title: `确定要删除${checkedKeys.value.length}个资产吗？`,
      content: '请注意：确认后，设备及其所有相关数据将不可恢复。',
      onOk: async () => {
        setProps({ loading: true });
        for (const item of checkedKeys.value) {
          await deleteAlarm(item.id);
        }
        reload();
        checkedKeys.value = [];
      },
    });
  }
  // 导出
  async function handleDownload({ alarmId }) {
    let excelArray: any[] = [];
    let params = {
      pagination: {
        page: 0,
        pageSize: 2147483647,
        sortProperty: 'createdTime',
        sortOrder: 'DESC',
      },
      alarmId: alarmId,
    };
    const alarmComment = await getAlarmComment(params);
    alarmComment.data.forEach((item) => {
      excelArray.push([
        item.type == 'SYSTEM'
          ? '系统'
          : item.firstName && item.lastName
          ? item.firstName + ' ' + item.lastName
          : item.email,
        dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
        item.comment?.editedOn ? dayjs(item.comment?.editedOn).format('YYYY-MM-DD HH:mm:ss') : '',
        item.comment?.text,
      ]);
    });
    aoaToSheetXlsx({
      data: excelArray,
      header: ['作者', '创建时间', '编辑时间', '文本'],
      filename: '告警.xlsx',
    });
  }

  onMounted(() => {
    if (props.isComponent) {
      setProps({
        api: entityAlarmsPage,
        formConfig: {
          showAdvancedButton: false,
          schemas: searchFormSchema,
          ...publicDrawerTableFormStyleSetting,
          actionColOptions: {
            md: { span: 12, offset: 0 },
            lg: { span: 8, offset: 0 },
            xl: { span: 6, offset: 12 },
            xxl: { span: 6, offset: 12 },
          },
        },
      });
    } else {
      setProps({
        api: alarmsPage,
      });
    }
  });
</script>
